<?php

namespace Ysy\Hyperf\Traits;

use Psr\Container\ContainerInterface;
use Throwable;
use Hyperf\Context\ApplicationContext;
use Hyperf\Logger\LoggerFactory;

use function Hyperf\Support\env;

trait ExceptionHandlerTrait
{
    /**
     * 获取容器实例
     */
    protected function getContainer(): ContainerInterface
    {
        return ApplicationContext::getContainer();
    }

    /**
     * 统一异常处理
     * 
     * @param Throwable $e 异常对象
     * @param string $logMessage 日志前缀
     * @param array $context 额外日志上下文
     */
    protected function handleException(
        Throwable $e,
        string $logMessage = '系统异常',
        array $context = []
    ) {
        // 获取日志服务
        $logger = $this->getContainer()->get(LoggerFactory::class)->get();

        // 记录异常信息
        $logger->error($logMessage, array_merge([
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ], $context));


        return [
            'code' => 500,
            'message' =>  env('TEST') !== 'YES_TEST' ? '系统服务暂时不可用，请稍后再试' : $e->getMessage()
        ];
    }

    /**
     * 只返回异常,不记录日志
     * 
     * @param Throwable $e 异常对象
     */
    protected function returnOnly(Throwable $e)
    {
        // 确定状态码
        $statusCode = $e->getCode() ?: 500;
        
        return [
            'code' => $statusCode,
            'message' => env('TEST') !== 'YES_TEST' ? '系统服务暂时不可用，请稍后再试' : $e->getMessage()
        ];
    }
}